package com.codez.xml;

import java.io.File;
import java.io.FileOutputStream;
import java.io.StringReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.apache.tomcat.util.http.fileupload.ByteArrayOutputStream;

/**
 * 简单编码,需要时完善
 * @author Admin
 *
 */
public class XmlUtils {

	public static String objectToXmlString(Object obj) {
		try {
			JAXBContext context = JAXBContext.newInstance(obj.getClass());
			Marshaller marshaller = context.createMarshaller();
//			Unmarshaller createUnmarshaller = context.createUnmarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
			ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
			marshaller.marshal(obj,outputStream);
			
			return new String(outputStream.toByteArray());
		} catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}
	
	public static boolean objectToFile(Object obj , File file) {
		try {
			JAXBContext context = JAXBContext.newInstance(obj.getClass());
			Marshaller marshaller = context.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
			marshaller.marshal(obj,new FileOutputStream(file));
			return true;
		} catch (Exception e) {
			// TODO: handle exception
		}
		return false;
	}
	
	public static <T> T readFromString(Class<T>  t , String obj) {
		try {
			JAXBContext context = JAXBContext.newInstance(t);
			Unmarshaller unmarshaller = context.createUnmarshaller();
			return (T) unmarshaller.unmarshal(new StringReader(obj));
		} catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}
	
	public static <T> T readFromFile(Class<T>  t , File file) {
		try {
			JAXBContext context = JAXBContext.newInstance(t);
			Unmarshaller unmarshaller = context.createUnmarshaller();
			return (T) unmarshaller.unmarshal(file);
		} catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}
	
	
}
